package com.ssm.practice.api.common;

import lombok.Data;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * 分页返回实体
 */
@Data //提供get方法才能被Json序列号
public class PageResult <T> implements Serializable {

    private Integer pageNo = 1; //页码，默认为1

    private Integer pageSize = 20; //页容量，默认为20

    private List<T> result = Collections.emptyList(); //查询内容，默认为空

    private Integer total = 0; //未分页情况下的总数

    private Integer totalPages = 0; //未分页情况下的总页数

    private Integer start = 1; //起始(记录本次查询第一条数据是第几条)

    private Integer end = 0; //结束(记录本次查询最后一条数据是第几条)

    //pageNo,pageSize可从入参获取，total，totalPages可从查询结果中获取
    public void setRecords(List<T> result) {
        this.result = result;
        if(result != null && result.size() > 0) {
            setTotal(result.size());
        }
    }

    public void setTotal(Integer size) {
        this.total = size;
        if(this.pageSize > 0) {
            this.totalPages = size / this.pageSize + (size % this.pageSize == 0 ? 0 : 1);
        }
        this.start = (this.pageSize > 0 ? (this.pageNo - 1) * this.pageSize : 0) + 1;
        this.end =  (this.start - 1 + this.pageSize * (this.pageNo > 0 ? 1 : 0));
    }

    //要把入参时的no，size传进来，所以要写set方法
    public void setPageNo(Integer pageNo) {
        if(pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        this.pageNo = pageNo;
    }
    public void setPageSize(Integer pageSize) {
        if(pageSize == null || pageSize < 1 || pageSize > Integer.MAX_VALUE) {
            pageSize = 20;
        }
        this.pageSize = pageSize;
    }

}
